﻿using AutoStar.Common;
using AutoStar.ViewModel;
using SharpGL.WPF;
using SharpGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Media.Media3D;
using Printer = AutoStar.Common.Printer;
using PrintProject = AutoStar.Common.PrintProject;
using Line3D = AutoStar.Common.Line3D;
using System.IO;
using SharpGL.SceneGraph.Lighting;

namespace AutoStar.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = Global.MainVM;
            this.Loaded += MainWindow_Loaded;
            this.Closing += Window_Closing;
            Global.MainVM.MainHeight = this.Width * 1.2;
            Global.MainVM.MainWidth = this.Height * 1.2;
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.FontSize = 17;
        }
        private void CreateBioStructureAnimation()
        {
            int lineNum = 100; // 线条数量
            Random random = new Random();
            Point range = new Point(ActualWidth, ActualHeight); // 窗口范围

            for (int i = 0; i < lineNum; i++)
            {
                Line line = new Line
                {
                    Stroke = new SolidColorBrush(Colors.LightBlue), // 线条颜色
                    StrokeThickness = 2,
                    Opacity = 0.5
                };

                // 随机生成起点和终点
                Point start = new Point(random.Next((int)range.X), random.Next((int)range.Y));
                Point end = new Point(random.Next((int)range.X), random.Next((int)range.Y));

                line.X1 = start.X;
                line.Y1 = start.Y;
                line.X2 = end.X;
                line.Y2 = end.Y;

                canvas.Children.Add(line);

                // 设置线条的动态移动动画
                DoubleAnimation x1Animation = new DoubleAnimation(start.X, random.Next((int)range.X), TimeSpan.FromSeconds(5))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };
                DoubleAnimation y1Animation = new DoubleAnimation(start.Y, random.Next((int)range.Y), TimeSpan.FromSeconds(5))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };
                DoubleAnimation x2Animation = new DoubleAnimation(end.X, random.Next((int)range.X), TimeSpan.FromSeconds(5))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };
                DoubleAnimation y2Animation = new DoubleAnimation(end.Y, random.Next((int)range.Y), TimeSpan.FromSeconds(5))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };

                line.BeginAnimation(Line.X1Property, x1Animation);
                line.BeginAnimation(Line.Y1Property, y1Animation);
                line.BeginAnimation(Line.X2Property, x2Animation);
                line.BeginAnimation(Line.Y2Property, y2Animation);
            }
        }
        private void CreateCellGrowthAnimation()
        {
            int cellNum = 150; // 细胞数量
            Random random = new Random();
            Point range = new Point(ActualWidth, ActualHeight); // 窗口范围

            for (int i = 0; i < cellNum; i++)
            {
                Ellipse cell = new Ellipse
                {
                    Width = 5,
                    Height = 5,
                    Fill = new SolidColorBrush(Colors.LightBlue),
                    Opacity = 0.8
                };

                // 随机生成初始位置
                Point position = new Point(random.Next((int)range.X), random.Next((int)range.Y));
                Canvas.SetLeft(cell, position.X);
                Canvas.SetTop(cell, position.Y);

                canvas.Children.Add(cell);

                // 设置细胞的生长动画
                DoubleAnimation growAnimation = new DoubleAnimation(5, 20, TimeSpan.FromSeconds(2))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };
                DoubleAnimation opacityAnimation = new DoubleAnimation(0.8, 0.3, TimeSpan.FromSeconds(2))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };

                cell.BeginAnimation(Ellipse.WidthProperty, growAnimation);
                cell.BeginAnimation(Ellipse.HeightProperty, growAnimation);
                cell.BeginAnimation(UIElement.OpacityProperty, opacityAnimation);

                // 设置细胞的移动动画
                DoubleAnimation moveX = new DoubleAnimation(position.X, random.Next((int)range.X), TimeSpan.FromSeconds(15))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };
                DoubleAnimation moveY = new DoubleAnimation(position.Y, random.Next((int)range.Y), TimeSpan.FromSeconds(15))
                {
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };

                cell.BeginAnimation(Canvas.LeftProperty, moveX);
                cell.BeginAnimation(Canvas.TopProperty, moveY);
            }
        }
        //private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        //{
        //    //CreateBioStructureAnimation();
        //    CreateCellGrowthAnimation();
        //    //CreateBioStructureAnimation();
        //    range = new Point(ActualWidth, ActualHeight);

        //    DispatcherTimer dispatcherTimerLine = new DispatcherTimer(TimeSpan.FromMilliseconds(50), DispatcherPriority.Normal, OnTimeTickLineOpacity, Dispatcher);
        //    dispatcherTimerLine.Start();
        //    var viewModel = this.DataContext as MainWindowVM;
        //    if (viewModel != null)
        //    {
        //        viewModel.LoginCommand.Execute(null);
        //    }
        //}
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Delay(1000);
            range = new Point(ActualWidth, ActualHeight);
            Ellipse lastEllipse = default(Ellipse);
            for (int i = 0; i < starNum; i++)
            {
                Point point = new Point(random.Next((int)range.X), random.Next((int)range.Y));
                Ellipse ellipse = new Ellipse();

                Canvas.SetLeft(ellipse, point.X);
                Canvas.SetTop(ellipse, point.Y);
                canvas.Children.Add(ellipse);
                ellipsePoints[ellipse] = new Point(random.Next(-5, 5), random.Next(-5, 5));
                while (ellipsePoints[ellipse] == default)
                {
                    ellipsePoints[ellipse] = new Point(random.Next(-5, 5), random.Next(-5, 5));
                }

                // 连线计算
                if (lastEllipse != default)
                {
                    Line line = new Line();
                    lines.Add(line);
                    line.SetBinding(Line.X1Property, new Binding("(Canvas.Left)") { Source = lastEllipse, Mode = BindingMode.OneWay });
                    line.SetBinding(Line.Y1Property, new Binding("(Canvas.Top)") { Source = lastEllipse, Mode = BindingMode.OneWay });
                    line.SetBinding(Line.X2Property, new Binding("(Canvas.Left)") { Source = ellipse, Mode = BindingMode.OneWay });
                    line.SetBinding(Line.Y2Property, new Binding("(Canvas.Top)") { Source = ellipse, Mode = BindingMode.OneWay });
                    Canvas.SetLeft(line, 4);
                    Canvas.SetTop(line, 4);
                    canvas.Children.Add(line);
                }

                lastEllipse = ellipse;


                // 动画计算
                int countTime = 1;
                Point offset = ellipsePoints[ellipse];
                while (point.X + offset.X > 0 && point.X + offset.X < range.X
                    && point.Y + offset.Y > 0 && point.Y + offset.Y < range.Y)
                {
                    point = new Point(point.X + offset.X, point.Y + offset.Y);
                    countTime++;
                }

                point = new Point(point.X + offset.X, point.Y + offset.Y);
                Storyboard storyboard = new Storyboard();
                storyboard.AutoReverse = true;
                storyboard.RepeatBehavior = RepeatBehavior.Forever;
                DoubleAnimation doubleAnimation = new DoubleAnimation() { To = point.X, Duration = new Duration(TimeSpan.FromMilliseconds(1000 * countTime)) };
                DoubleAnimation doubleAnimationY = new DoubleAnimation() { To = point.Y, Duration = new Duration(TimeSpan.FromMilliseconds(1000 * countTime)) };

                storyboard.Children.Add(doubleAnimation);
                storyboard.Children.Add(doubleAnimationY);
                Storyboard.SetTarget(doubleAnimation, ellipse);
                Storyboard.SetTarget(doubleAnimationY, ellipse);

                Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
                Storyboard.SetTargetProperty(doubleAnimationY, new PropertyPath("(Canvas.Top)"));
                storyboard.Begin(ellipse);

            }
            DispatcherTimer dispatcherTimerLine = new DispatcherTimer(TimeSpan.FromMilliseconds(50), DispatcherPriority.Normal, OnTimeTickLineOpacity, Dispatcher);
            dispatcherTimerLine.Start();
            var viewModel = this.DataContext as MainWindowVM;
            if (viewModel != null)
            {
                viewModel.LoginCommand.Execute(null);
            }
        }
        public static Printer printer = Global.printer;//打印机
        public static PrintProject printProject = Global.printProject;//打印项目
        System.Timers.Timer timer = new System.Timers.Timer(interval: 2000);//用于检测是否是打印中空闲的定时器
        System.Timers.Timer timerIsStop = new System.Timers.Timer(interval: 100);
        System.Timers.Timer closeSolidfyLight = new System.Timers.Timer(100);
        Random random = new Random();
        Point range = new Point(800, 450);
        int starNum = 200;
        Dictionary<Ellipse, Point> ellipsePoints = new Dictionary<Ellipse, Point>();
        List<Line> lines = new List<Line>();
        private void OnTimeTickLineOpacity(object sender, EventArgs e)
        {
            int index = 0;
            foreach (var item in ellipsePoints)
            {
                if (index > 0)
                {
                    var ellpses = ellipsePoints.Keys.ToList();
                    var firstPoint = new Point(Canvas.GetLeft(ellpses[index - 1]), Canvas.GetTop(ellpses[index - 1]));
                    var secPoint = new Point(Canvas.GetLeft(ellpses[index]), Canvas.GetTop(ellpses[index]));

                    double dist = Math.Sqrt(Math.Pow(firstPoint.X - secPoint.X, 2) + Math.Pow(firstPoint.Y - secPoint.Y, 2));
                    var currentLine = lines[index - 1];

                    if (dist > 200)
                    {
                        currentLine.Opacity = 0;
                    }
                    else
                    {
                        currentLine.Opacity = 1 - (dist / 200);
                    }
                }
                index++;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = false;
        }

        private void ListBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var listBox = sender as ListBox;
            if (listBox != null)
            {
                // 获取被点击的ListBoxItem  
                var hitTestResult = VisualTreeHelper.HitTest(listBox, e.GetPosition(listBox));
                if (hitTestResult != null && hitTestResult.VisualHit is ListBoxItem item)
                {
                    // 如果该项已经被选中，则取消选中  
                    if (listBox.SelectedItems.Contains(item))
                    {
                        listBox.SelectedItem = null; // 或者使用 listBox.UnselectAll(); 如果支持多选  
                        e.Handled = true; // 标记事件已处理，防止默认选中行为  
                    }
                }
            }
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.FontSize = e.NewSize.Width / 70;
            foreach (var menuItem in myMenu.Items.OfType<MenuItem>())
            {
                menuItem.FontSize = e.NewSize.Width / 70;
            }
            foreach (var child in btn_stack.Children)
            {
                if (child is Button button)
                {
                    if (e.PreviousSize.Width > 0)
                        button.Width = e.NewSize.Width / e.PreviousSize.Width * button.Width;
                }
            }
        }
    }
}
